package com.gs.m_home.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.fragment.app.Fragment
import com.gs.common.constant.ActionConst
import com.gs.common.global.GlobalVariables
import com.gs.common.util.DialogUtil
import com.gs.common.util.ToastUtil
import com.gs.m_home.R
import com.gs.m_home.callback.OnDoGetUserinfoStateCallback
import com.gs.m_home.callback.OnDoLogoutStateCallback
import com.gs.m_home.persistent.MinePersistent

class MineFragment : Fragment() {

    private val minePersistent by lazy { MinePersistent.getInstance(requireContext()) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.mine_fragment, container, false)

        // 注销登录按钮
        val logoutBtn = view.findViewById<LinearLayout>(R.id.logout_btn)
        logoutBtn.setOnClickListener {
            logout(requireContext())
        }
        // 改变order detail drawable的颜色
        val orderDetailDrawable = changeDrawableColor(
            requireContext(),
            R.drawable.order_detail,
            com.gs.common.R.color.order_blue
        )
        setImageDrawableByControllerId(view, R.id.order_detail_img, orderDetailDrawable)
        // 改变aftermarket drawable的颜色
        val aftermarketDrawable = changeDrawableColor(
            requireContext(),
            R.drawable.aftermarket_img,
            com.gs.common.R.color.aftermarket_pink
        )
        setImageDrawableByControllerId(view, R.id.aftermarket_img, aftermarketDrawable)
        // 改变collection drawable的颜色
        val collectionDrawable = changeDrawableColor(
            requireContext(),
            R.drawable.collection_img,
            com.gs.common.R.color.collection_yellow
        )
        setImageDrawableByControllerId(view, R.id.collection_img, collectionDrawable)

        // 设置个人详细信息界面
        val userDetails = view.findViewById<LinearLayout>(R.id.user_details)
        userDetails.setOnClickListener {
            toTargetActionActivity(ActionConst.TO_PERSON_DETAILS_ACTIVITY_ACTION)
        }

        // 设置全部订单界面
        val orderList = view.findViewById<RelativeLayout>(R.id.order_list)
        orderList.setOnClickListener {
            toTargetActionActivity(ActionConst.TO_ORDER_LIST_ACTIVITY_ACTION)
        }

        // 设置我的商品界面
        val myGoods = view.findViewById<RelativeLayout>(R.id.my_goods)
        myGoods.setOnClickListener {
            toTargetActionActivity(ActionConst.TO_MY_GOODS_ACTIVITY_ACTION)
        }

        // 设置修改密码
        val changePassword = view.findViewById<LinearLayout>(R.id.change_password_btn)
        changePassword.setOnClickListener {
            toTargetActionActivity(ActionConst.TO_CHANGE_PASSWORD_ACTIVITY_ACTION)
        }
        return view
    }

    override fun onResume() {
        super.onResume()
        // 设置个人信息
        setPersonInformation(requireView())
    }

    private fun setPersonInformation(view: View) {
        minePersistent.getUserInfo(object : OnDoGetUserinfoStateCallback{
            @SuppressLint("SetTextI18n", "UseCompatLoadingForDrawables")
            override fun onGetUserinfoSuccess() {
                val userNickname = view.findViewById<TextView>(R.id.user_nickname)
                val username = view.findViewById<TextView>(R.id.username)
                val businessImg = view.findViewById<ImageView>(R.id.business_img)
                val businessAuthority = view.findViewById<LinearLayout>(R.id.business_authority)
                val businessAuthorityUnderline = view.findViewById<View>(R.id.business_authority_underline)
                userNickname.text = GlobalVariables.loginUser?.nickname ?: "用户123"
                username.text = "用户名: ${GlobalVariables.loginUser?.userName}"
                val businessFlag = GlobalVariables.loginUser?.isBusiness ?: false
                if (businessFlag){
                    businessImg.setImageDrawable(resources.getDrawable(com.gs.common.R.drawable.business_active))
                    businessAuthorityUnderline.visibility = View.VISIBLE
                    businessAuthority.visibility = View.VISIBLE
                } else {
                    businessImg.setImageDrawable(resources.getDrawable(com.gs.common.R.drawable.business_inactive))
                    businessAuthorityUnderline.visibility = View.GONE
                    businessAuthority.visibility = View.GONE
                }
//                ToastUtil.showShortToast(requireContext(), "用户信息更新成功")
            }

            override fun onGetUserinfoFailed() {
                ToastUtil.showShortToast(requireContext(), "用户信息更新失败")
            }

            override fun onNetworkError() {
                ToastUtil.showShortToast(requireContext(), "无法连接网络！")
            }

            override fun onServerError() {
                ToastUtil.showShortToast(requireContext(), "无法连接服务器！")
            }
        })
    }

    private fun toTargetActionActivity(targetAction: String) {
        val intent = Intent().apply {
            action = targetAction
        }
        startActivity(intent)
    }

    private fun logout(context: Context) {
        val alertDialog = DialogUtil.createCommonAlertDialog(requireContext(), "注销", "当前账号") {
            if (it == DialogUtil.CONFIRM_TO_DO) {
                minePersistent.userLogout(object : OnDoLogoutStateCallback{
                    override fun onLogoutSuccess() {
                        val intent = Intent().apply {
                            action = ActionConst.TO_INDEX_ACTIVITY_ACTION
//            下面是启用第三方App方式
//            action = Intent.ACTION_MAIN
//            addCategory(Intent.CATEGORY_LAUNCHER)
//            component = ComponentName("com.gs.litchi_source", "com.gs.m_index.IndexActivity")
                        }
                        startActivity(intent)
                        ToastUtil.showShortToast(context, "注销登录成功！")
                        requireActivity().finish()
                    }

                    override fun onLogoutFailed() {
                        ToastUtil.showShortToast(context, "注销登录失败！")
                    }

                    override fun onNetworkError() {
                        ToastUtil.showShortToast(context, "无法连接网络！")
                    }

                    override fun onServerError() {
                        ToastUtil.showShortToast(context, "无法连接服务器！")
                    }
                })
            }
        }
        alertDialog.show()
    }

    private fun setImageDrawableByControllerId(
        view: View,
        controllerId: Int,
        drawable: Drawable?
    ): Boolean {
        val imgView = view.findViewById<ImageView>(controllerId)
        return if (imgView != null) {
            imgView.setImageDrawable(drawable)
            true
        } else {
            false
        }
    }

    private fun changeDrawableColor(
        context: Context,
        drawableResId: Int,
        colorResId: Int
    ): Drawable {
        val drawable = ContextCompat.getDrawable(context, drawableResId)
        val color = ContextCompat.getColor(context, colorResId)
        try {
            val wrappedDrawable = DrawableCompat.wrap(drawable!!)
            DrawableCompat.setTint(wrappedDrawable, color)
            return wrappedDrawable
        } catch (e: Exception) {
            throw Exception("资源不存在！")
        }
    }
}